<template>
  <van-popup v-model:show="showPopup" position="right" destroy-on-close :style="{ width: '100%', height: '100%' }" teleport="body">
    <van-nav-bar :title="tradeType === 1 ? '买入' : '卖出'" fixed @click-right="showPopup = false">
      <template #right>
        <van-icon name="cross" size="18" />
      </template>
    </van-nav-bar>
    <div class="form-wrapper">
      <van-cell-group v-if="userType === 'admin'" class="mb-10">
        <van-field label="产品名称" v-model="form.showProductName" colon readonly />
        <van-field label="产品代码" v-model="form.showProductCode" colon readonly />
        <van-field label="单位净值" v-model="form.currentNetValue" colon readonly />
      </van-cell-group>
      <van-cell-group v-if="tradeType === 2" class="mb-10">
        <van-field label="盈亏" v-model="form.showProductProfitLoss" colon readonly>
          <template #input>
            <span>{{ formatAmountBySize(form.showProductProfitLoss || 0) }}</span>
          </template>
          <template #right-icon>
            <span>{{ formatAmountTextBySize(form.showProductProfitLoss || 0) }}</span>
          </template>
        </van-field>
        <van-field label="当前资产" v-model="form.assets" colon readonly>
          <template #input>
            <span>{{ formatAmountBySize(form.assets || 0) }}</span>
          </template>
          <template #right-icon>
            <span>{{ formatAmountTextBySize(form.assets || 0) }}</span>
          </template>
        </van-field>
      </van-cell-group>
      <van-form @submit="onSubmit">
        <van-cell-group>
          <van-field
            v-model="params.transactionNetValue"
            label="成交净值"
            colon
            type="number"
            placeholder="请选择日期"
            readonly
            :rules="[{ required: true, message: '请选择日期' }]"
            @update:model-value="onTransactionNetValueInput"
          />
          <van-field
            v-model="params.transactionDate"
            :label="tradeType === 1 ? '买入日期' : '卖出日期'"
            colon
            readonly
            right-icon="calendar-o"
            placeholder="点击选择时间"
            :rules="[{ required: true, message: '请选择日期' }]"
            @click="showDatePicker = true"
          />
          <van-field
            v-model="params.transactionAmount"
            :label="tradeType === 1 ? '买入金额' : '卖出金额'"
            colon
            placeholder="请输入金额"
            :rules="[{ required: true, message: '请输入金额' }]"
            @update:model-value="onTransactionAmountInput"
          >
            <template #right-icon>
              <span>元</span>
            </template>
          </van-field>
          <van-field
            v-model="params.transactionUnits"
            :label="tradeType === 1 ? '买入份额' : '卖出份额'"
            colon
            type="number"
            placeholder="请输入份额"
            :rules="[{ required: true, message: '请输入份额' }]"
            @update:model-value="onTransactionUnitsInput"
          >
            <template #right-icon>
              <span>份</span>
            </template>
          </van-field>
        </van-cell-group>
        <div class="btn-wrapper">
          <van-button class="btn-item" block type="default" @click="showPopup = false"> 取消 </van-button>
          <van-button class="btn-item" block type="primary" native-type="submit"> 确定 </van-button>
        </div>
      </van-form>
      <van-calendar v-model:show="showDatePicker" title="选择日期" :default-date="new Date()" :min-date="new Date(dayjs('2020-01-01'))" :max-date="new Date(dayjs().add(-1, 'day'))" :formatter="datePickerFormatter" @confirm="onDatePickerConfirm" />
      
    </div>
  </van-popup>
</template>

<script setup>
import { ref } from 'vue'
import { apiAdminBuyProduct, apiAdminSellProduct, apiGetProductTransactionLogListById } from '@/api/product'
import { apiCustomerBuyProduct, apiCustomerSellProduct, apiGetSimulatedTransactionLogListByUserId } from '@/api/customer'
import { apiGetProductNetByIdAndDate } from '@/api/productNet'
import { showToast } from 'vant'
import dayjs from 'dayjs'
import { deepClone, formatAmountBySize, formatAmountTextBySize } from '@/utils/common'
import store from '@/stores'
import { storeToRefs } from 'pinia'
import { times, plus, minus } from '@/utils/calc'

const emit = defineEmits(['refresh'])

const props = defineProps({
  userType: {
    type: String,
    default: 'admin'
  }
})

const showPopup = ref(false)
const form = ref({})
// 1 买入 2 卖出
const tradeType = ref(1)
const showDatePicker = ref(false)
const pickerValue = ref([dayjs().get('year'), dayjs().get('month') + 1, dayjs().get('date')])
const isDateHaveNet = ref(false)
// 交易记录
const transactionLogList = ref([])

const { slbInfo } = storeToRefs(store.product)

const params = ref({
  id: '',
  simulatedProductId: '',
  userId: '',
  transactionNetValue: '',
  transactionDate: '',
  transactionUnits: '',
  transactionAmount: ''
})

const open = (detail, type) => {
  form.value = detail
  tradeType.value = type
  if (type === 2) {
    getSimulatedTransactionLogList()
  }
  if (props.userType === 'admin') {
    form.value.showProductName = detail.productNameAlias || detail.productName
    form.value.showProductCode = detail.productCodeAlias || detail.productCode
    form.value.symbol = !detail.productProfitLoss ? '' : detail.productProfitLoss > 0 ? '+' : '-'
    form.value.showProductProfitLoss = `${form.value.symbol}${Math.abs(detail.productProfitLoss || 0)}`
    form.value.assets = times(detail.holdingUnits, detail.currentNetValue)
    params.value.id = detail.id
    params.value.transactionNetValue = '' // detail.currentNetValue
  } else {
    form.value.showProductName = slbInfo.value.productName
    form.value.showProductCode = slbInfo.value.productCode
    form.value.symbol = !detail.profitLoss ? '' : detail.profitLoss > 0 ? '+' : '-'
    form.value.showProductProfitLoss = `${form.value.symbol}${Math.abs(detail.profitLoss || 0)}`
    form.value.assets = detail.assets
    params.value.userId = detail.id
    params.value.simulatedProductId = 1
    params.value.transactionNetValue = '' //slbInfo.value.currentNetValue
  }
  params.value.transactionDate = ''
  params.value.transactionUnits = ''
  params.value.transactionAmount = ''
  showPopup.value = true
}

const datePickerFormatter = (day) => {
  if ([6, 0].includes(dayjs(day.date).day())) {
    day.type = 'disabled'
  }
  return day
}

const onDatePickerConfirm = (selectedValues) => {
  pickerValue.value = selectedValues
  params.value.transactionDate = dayjs(pickerValue.value).format('YYYY/MM/DD')
  showDatePicker.value = false
  // 获取对应日期的净值
  getNetValueByDate(params.value.transactionDate)
}

const getNetValueByDate = (date) => {
  let result
  if (props.userType === 'admin') {
    result = apiGetProductNetByIdAndDate({ productId: form.value.id, netDate: dayjs(date).format('YYYY-MM-DD'), productType: 1 })
  } else {
    result = apiGetProductNetByIdAndDate({ productId: 1, netDate: dayjs(date).format('YYYY-MM-DD'), productType: 2 })
  }
  result.then((res) => {
    if (res) {
      params.value.transactionNetValue = res
      isDateHaveNet.value = true
    } else {
      showToast({
        message: '所选日期无净值数据，禁止交易，请补齐净值数据',
        position: 'top'
      })
      isDateHaveNet.value = false
      params.value.transactionNetValue = ''
    }
  })
}

/**
 * 获取交易信息
 */
const getSimulatedTransactionLogList = () => {
  let result
  if (props.userType === 'admin') {
    result = apiGetProductTransactionLogListById({ id: form.value.id })
  } else {
    result = apiGetSimulatedTransactionLogListByUserId({ id: form.value.id })
  }
  result.then((res) => {
    transactionLogList.value = res
  })
} 

const onTransactionUnitsInput = (val) => {
  params.value.transactionAmount = ((params.value.transactionNetValue || 0) * val).toFixed(4)
  if (tradeType.value === 2) {
    // 计算盈亏
    let cost = 0 // 成本
    let units = val // 卖出份额
    for (let i = 0; i < transactionLogList.value.length; i++) {
      const item = transactionLogList.value[i]
      if (units < item.redeemableUnits) {
        cost = plus(cost, times(units, item.transactionNetValue))
        break
      }
      units = minus(units, item.redeemableUnits)
      cost = plus(cost, times(item.redeemableUnits, item.transactionNetValue))
    }
    const profitLoss = minus(times(val || 0, params.value.transactionNetValue), cost)
    form.value.symbol = !profitLoss ? '' : profitLoss > 0 ? '+' : '-'
    form.value.showProductProfitLoss = `${form.value.symbol}${Math.abs(profitLoss || 0)}`
  }
}

const onTransactionAmountInput = (val) => {
  params.value.transactionUnits = ((val || 0) / params.value.transactionNetValue).toFixed(2)
  if (tradeType.value === 2) {
    // 计算盈亏
    let cost = 0 // 成本
    let units = params.value.transactionUnits // 卖出份额
    for (let i = 0; i < transactionLogList.value.length; i++) {
      const item = transactionLogList.value[i]
      if (units < item.redeemableUnits) {
        cost = plus(cost, times(units, item.transactionNetValue))
        break
      }
      units = minus(units, item.redeemableUnits)
      cost = plus(cost, times(item.redeemableUnits, item.transactionNetValue))
    }
    const profitLoss = minus(times(params.value.transactionUnits || 0, params.value.transactionNetValue), cost)
    form.value.symbol = !profitLoss ? '' : profitLoss > 0 ? '+' : '-'
    form.value.showProductProfitLoss = `${form.value.symbol}${Math.abs(profitLoss || 0)}`
  }
}

const onTransactionNetValueInput = (val) => {
  params.value.transactionAmount = ((val || 0) * params.value.transactionUnits).toFixed(4)
}

const onSubmit = () => {
  let paramsClone = deepClone(params.value)
  paramsClone.transactionDate = dayjs(paramsClone.transactionDate).format('YYYY-MM-DD')
  // 如果是卖出，判断卖出份额是否超过当前持有份额
  if (tradeType.value === 2 && paramsClone.transactionUnits > form.value.holdingUnits) {
    showToast({
      message: `卖出份额不能超过当前持有份额[${form.value.holdingUnits}]`,
      position: 'top'
    })
    return
  }
  let result
  if (props.userType === 'admin') {
    if (tradeType.value === 1) {
      result = apiAdminBuyProduct(paramsClone)
    } else {
      paramsClone.transactionUnits = -params.value.transactionUnits
      paramsClone.transactionAmount = -params.value.transactionAmount
      result = apiAdminSellProduct(paramsClone)
    }
  } else {
    if (tradeType.value === 1) {
      result = apiCustomerBuyProduct(paramsClone)
    } else {
      paramsClone.transactionUnits = -params.value.transactionUnits
      paramsClone.transactionAmount = -params.value.transactionAmount
      result = apiCustomerSellProduct(paramsClone)
    }
  }
  result.then((res) => {
    showToast({
      message: '操作成功',
      position: 'top'
    })
    setTimeout(() => {
      showPopup.value = false
      emit('refresh')
    }, 500)
  })
}

defineExpose({
  open
})

</script>

<style lang="less" scoped>
.form-wrapper {
  padding-top: var(--van-nav-bar-height);
  background-color: #f7f7f7;
  .btn-wrapper {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    background-color: white;
    .btn-item {
      width: 47%;
    }
  }
}
</style>
